// 发票信息  发票地址选择
<template>
  <div class="container">
    <h4>发票信息</h4>
    <p class="careful">
      <span>*</span>如需开具增值税专用发票 请提供一般纳税人证明 >
      <i @click="submit">证明提交 》个人中心 》纳税人证明提交证明材料</i>
    </p>
    <div class="InvoiceK">
      <div class="deshk">
        <span>发票类型：</span>
        <el-button
          @click="selectMethods(index,btn)"
          size="small"
          :class=" index == act ?'active':''"
          v-for="(btn,index) in btnz"
          :key="index"
        >{{btn}}</el-button>
      </div>

      <div class="deshk">
        <form class="taitou">
          <div v-if="show1">
            <label>身份证号：</label>
            <el-input size="mini" placeholder="居民身份证号码..." v-model="id_card" @blur="idCard"></el-input>
          </div>
          <br>
          <div v-if="show2">
            <label>发票抬头：</label>
            <el-input size="mini" placeholder="发票抬头..." v-model="invoice_rise" @blur="InvoiceRise"></el-input>
          </div>
          <p style="color:#f40;font-size:12px;" v-if="show1">*温馨提示：个人 普通增值税发票必须需要填写身份证号码   公司 普通增值发票可以不填写身份证号码......</p>
        </form>

        <!-- 那一条虚线 -->
        <h6 v-show="act !== 2"></h6>

        <h5 v-show="act !== 2">
          <span>发票寄送地址：</span>
          <i>{{defaultAddress}}</i>
          <el-button type="text" class="set" size="mini" @click="dialogFormVisible7 = true">设置</el-button>
        </h5>

        <p style="font-size:12px;color:red;">*系统默认发票寄送地址与产品收货地址一致；不一致时，发票邮寄费用请买家自行承担。</p>
        <div class="DiologS">
          <el-dialog title="选择地址" :visible.sync="dialogFormVisible7">
            <div class="dialogk">
              <ul class="content-left">
                <li v-for="(item,index) in getAddressData" :key="index">
                  <el-radio-group v-model="radio">
                    <el-radio
                      :label="index"
                    >{{item.province_name}}{{item.city_name}}{{item.district_name}}{{item.address}}{{item.consignee}}（收）{{item.phone}}</el-radio>
                  </el-radio-group>
                  <div>
                    <el-button size="mini" type="warning" @click="edit(item.id)">编 辑</el-button>
                    <el-button size="mini" type="danger" @click="del(item.id)">删 除</el-button>
                  </div>
                </li>
              </ul>
              <!-- <el-button type="text" @click="NewAddress" ><i>+</i> 新增地址</el-button> -->
              <!-- <el-button type="text" @click="dialogFormVisible8 = true" ><i>+</i> 新增地址</el-button> -->
              <el-button type="text" @click="NewAddress">
                <i>+</i> 新增地址
              </el-button>
            </div>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible7 = false">取 消</el-button>
              <el-button type="primary" @click="AddressSelection">确 定</el-button>
              <!-- <el-button type="primary" @click="dialogFormVisible7 = false">确 定</el-button> -->
            </div>
          </el-dialog>
          <el-dialog title="新增地址" :visible.sync="dialogFormVisible8">
            <div
              class="dialogk2"
              v-loading="loading2"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.3)"
            >
              <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item label="收货人" prop="name">
                  <el-input v-model="ruleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="tel">
                  <el-input v-model="ruleForm.tel"></el-input>
                </el-form-item>
                <el-form-item label="所在地区" prop="region">
                  <el-select
                    @change="region1"
                    v-model="ruleForm.region1.id"
                    placeholder="请选择省份"
                    size="mini"
                  >
                    <el-option
                      v-for="item in ruleForm.region1"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>

                  <el-select
                    @change="region2"
                    v-model="ruleForm.region2.id"
                    placeholder="请选择城市"
                    size="mini"
                  >
                    <el-option
                      v-for="item in ruleForm.region2"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>

                  <el-select
                    @change="region3"
                    v-model="ruleForm.region3.id"
                    placeholder="请选择所在区"
                    size="mini"
                  >
                    <el-option
                      v-for="item in ruleForm.region3"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="详细地址" prop="desc">
                  <el-input type="textarea" v-model="ruleForm.desc"></el-input>
                </el-form-item>
                <el-form-item label="默 认">
                  <el-switch v-model="ruleForm.value"></el-switch>
                  <el-button
                    type="primary"
                    size="mini"
                    style="margin-left:40px"
                    @click="getReceivingAddress"
                  >同收货地址</el-button>
                </el-form-item>
              </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible8 = false">取 消</el-button>
              <!-- <el-button type="primary" @click="dialogFormVisible8 = false">确 定</el-button> -->
              <el-button type="danger" v-if="!conversion" @click="newAddressConfirmation">确 定</el-button>
              <el-button type="primary" v-else @click="editConfirmation">确 定</el-button>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// import elDialogs from "./elDialogs"
export default {
  name: "InvoiceInfo",
  props: [
    "DefaultAddress",
    "changesUser",
    "ReceivingAddressID"
  ],

  data() {
    return {
      ruleForm9: {
        Image: '',
      },
      addressId: '',  // 发票地址id存储
      id_card: null,  // 身份证号
      invoice_rise: null, // 发票抬头
      flag: null,   // 发票的显示哪一个按钮
      loading2: false,  // 加载中的动画
      editId: "",
      conversion: "",
      defaultAddress: "", // 默认地址
      radio: "1", // 默认地址的位置
      getAddressData: [], // 获取地址存储的数组
      AddressCombination: [], // 地址组合放进这个里面      后期把这个数组给后台就好
      dialogFormVisible7: false,
      dialogFormVisible8: false,
      dialogFormVisible9: false,
      show1: false,
      show2: false,
      show3: false,
      act: 2,   //发票类型的 选项的 active
      btnz: ["增值税普通发票", "增值税专用发票", "不开发票"],


      ruleForm: {
        //
        name: "",
        tel: "",
        region1: [],
        region2: [],
        region3: [],
        desc: "",
        value: false
      },
      rules: {
        name: [
          { required: true, message: "请输入收货人姓名", trigger: "blur" }
        ],
        tel: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
        region1: [
          { required: true, message: "请选择活动区域", trigger: "change" }
        ],
        region2: [
          { required: true, message: "请选择活动区域", trigger: "change" }
        ],
        region3: [
          { required: true, message: "请选择活动区域", trigger: "change" }
        ],
        desc: [{ required: true, message: "请填写活动形式", trigger: "blur" }]
      }
    }
  },

  methods: {
    // 确定所显示的按钮
    filterButton(flag = 2) {
      this.flag = flag
      if ([1, 3, 4].includes(this.flag)) {
        this.btnz = ["增值税普通发票", "不开发票"]

      } else {
        this.btnz = ["增值税专用发票", "不开发票"]
      }
    },

    // 获取发票的资质
    async getInvoice() {
      let user_id = this.$store.state.UserInfor.user_id
      let res = await this.$http({
        method: 'post',
        url: '/api//api/index/web/invoice',
        data: {
          user_id
        }
      })
      console.log(res)
      if (res.data.State.Code == 200) {
        console.log(res.data)
        // this.filterButton(res.data.data)              // 获取发票资质 的函数执行
      }
    },

    // 增值税专用发票证明提交
    submit() {
      this.$router.push({
        name: "MyCenter",
        params: {
          id: "0"
        }
      })
    },

    // 身份证号
    idCard() {
      this.$store.commit("id_card", this.id_card)
    },

    // 发票抬头
    InvoiceRise() {
      this.$store.commit("invoiceRise", this.invoice_rise)
    },

    // 同收货地址的点击事件   大写区分
    async getReceivingAddress() {
      this.loading2 = true
      const res = this.$store.state.changesAddress
      let from = this.ruleForm
      console.log(res)
      from.name = res.consignee
      from.tel = res.phone
      from.desc = res.address

      from.region1.id = res.province_id
      this.$http.all([this.region1(res.province_id)])
        .then(this.$http.spread((acct, perms) => {
          this.$http.all([this.region2(res.city_id)])
            .then(this.$http.spread((acct, perms) => {
              this.$http.all([this.region3(res.district_id)])
                .then(this.$http.spread((acct, perms) => {
                  this.newAddressConfirmation()
                  this.loading2 = false
                }))
            }))
        }))
    },

    // 地址选择
    AddressSelection() {
      this.dialogFormVisible7 = false
      const oldAddress = this.getAddressData[this.radio]
      // console.log(oldAddress.id)
      this.$emit("InvoiceInfoIDChange", oldAddress.id)
      this.defaultAddress = `
        ${oldAddress.province_name} 
        ${oldAddress.city_name}  
        ${oldAddress.district_name} 
        ${oldAddress.address}
        ${oldAddress.consignee}
        ${oldAddress.phone}
      `
    },

    // 新增地址
    NewAddress() {
      this.dialogFormVisible8 = true
      this.conversion = false
      this.ruleForm.name = ""
      this.ruleForm.tel = ""
      this.ruleForm.desc = ""
    },

    // 新增地址的确认
    async newAddressConfirmation() {
      console.log(this.AddressCombination)
      let [
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      ] = [
          this.$store.state.UserInfor.user_id,
          this.ruleForm.name,
          this.AddressCombination["province"].id,
          this.AddressCombination["province"].name,
          this.AddressCombination["city"].id,
          this.AddressCombination["city"].name,
          this.AddressCombination["area"].id,
          this.AddressCombination["area"].name,
          this.ruleForm.desc,
          this.ruleForm.tel,
          2,
          ""
        ]

      if (this.ruleForm.value) {
        is_default = "1"
      } else {
        is_default = "0"
      }
      let obj = {
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      }
      let arr = Object.values(obj)

      if (arr.includes("")) {
        this.$notify({
          title: "警告",
          message: "请填写完整的地址信息",
          type: "warning"
        })
        return
      }

      let addAddress = await this.$http({
        method: "post",
        url: "/api/home/index/saveaddress",
        data: {
          user_id, //用户ID
          consignee, //收货人
          province_id, //省份id
          province_name, //省份名称
          city_id, //城市id
          city_name, //城市名称
          district_id, //地区id
          district_name, //地区名称
          address, //详细地址
          phone, //联系电话
          type, //1：收货地址，2：发票地址
          is_default //默认地址 0：不默认，1：默认
        }
      })
      if (addAddress.data.State.Code == 200) {
        this.dialogFormVisible8 = false
        this.$notify({
          title: "成功",
          message: "成功增加地址...",
          type: "success"
        })
      }
      this.getAddress()
    },

    // 获取发票地址
    async getAddress() {
      const user_id = this.$store.state.UserInfor.user_id
      let address = await this.$http({
        method: "post",
        url: "/api/home/index/getaddresslist",
        data: {
          user_id,
          type: "2"
        }
      })
      if (address.data.State.Code == 200) {
        this.getAddressData = address.data.data
        this.getAddressData.forEach((element, index) => {
          if (element.is_default == 1) {
            this.defaultAddress = `
              ${element.province_name} 
              ${element.city_name} 
              ${element.district_name} 
              ${element.address}
              ${element.consignee} 
              ${element.phone}
            `
            this.radio = index
            const oldAddress = this.getAddressData[this.radio]
            // console.log(oldAddress.id)
            this.addressId = oldAddress.id

          }
        })
      }
      // console.log(this.getAddressData)
    },

    // 地址删除按钮的操作
    async del(transmitId) {
      let user_id = this.$store.state.UserInfor.user_id
      let id = transmitId
      const delRes = await this.$http({
        method: "post",
        url: "/api/home/index/deladdress",
        data: {
          user_id,
          id
        }
      })
      if (delRes.data.State.Code == 200) {
        this.$notify({
          title: "成功",
          message: "成功刪除该地址...",
          type: "success"
        })
      }
      console.log(delRes)
      this.getAddress()
    },

    // 地址编辑按钮的处理
    edit(transmitId) {
      this.conversion = true
      this.dialogFormVisible8 = true
      this.editId = transmitId
    },

    // 编辑确认按钮事件
    async editConfirmation() {
      this.conversion = false
      let [
        id,
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      ] = [
          this.editId,
          this.$store.state.UserInfor.user_id,
          this.ruleForm.name,
          this.AddressCombination["province"].id,
          this.AddressCombination["province"].name,
          this.AddressCombination["city"].id,
          this.AddressCombination["city"].name,
          this.AddressCombination["area"].id,
          this.AddressCombination["area"].name,
          this.ruleForm.desc,
          this.ruleForm.tel,
          2,
          ""
        ]

      if (this.ruleForm.value) {
        is_default = "1"
      } else {
        is_default = "0"
      }
      console.log(
        id,
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default
      ) //默认地址 0：不默认，1：默认
      let obj = {
        id,
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      }
      let arr = Object.values(obj)
      if (arr.includes("")) {
        this.$notify({
          title: "警告",
          message: "请填写完整的地址信息",
          type: "warning"
        })
        return
      }

      let addAddress = await this.$http({
        method: "post",
        url: "/api/home/index/editaddress",
        data: {
          id,
          user_id, //用户ID
          consignee, //收货人
          province_id, //省份id
          province_name, //省份名称
          city_id, //城市id
          city_name, //城市名称
          district_id, //地区id
          district_name, //地区名称
          address, //详细地址
          phone, //联系电话
          type, //1：收货地址，2：发票地址
          is_default //默认地址 0：不默认，1：默认
        }
      })
      console.log(addAddress)
      if (addAddress.data.State.Code == 200) {
        console.log(addAddress)
        this.dialogFormVisible8 = false
        this.$notify({
          title: "成功",
          message: "成功修改地址...",
          type: "success"
        })
      }
    },

    // 通过id匹配名字
    SearchItem(pid, obj) {
      let mySearchItem = obj.find(obj => {
        return obj.id === pid
      })
      return mySearchItem
    },

    async region1(paramID) {
      let pid = this.ruleForm.region1.id || paramID
      console.log(pid)
      let obj = this.ruleForm.region1
      this.SearchItem(pid, obj)

      this.AddressCombination["province"] = this.SearchItem(pid, obj)
      // console.log(this.AddressCombination)

      // console.log(pid)
      let Province = await this.$http({
        method: "post",
        url: "/api/home/index/linkagearea",
        data: {
          pid
        }
      })
      const myProvince = Province.data
      if (myProvince.State.Code == 200) {
        this.ruleForm.region2 = myProvince.data
      }
    },

    async region2(paramID) {
      let pid = this.ruleForm.region2.id || paramID
      let obj = this.ruleForm.region2
      this.SearchItem(pid, obj)

      this.AddressCombination["city"] = this.SearchItem(pid, obj)
      // console.log(this.AddressCombination)

      let Province = await this.$http({
        method: "post",
        url: "/api/home/index/linkagearea",
        data: {
          pid
        }
      })
      const myProvince = Province.data
      if (myProvince.State.Code == 200) {
        console.log(myProvince.data)
        this.ruleForm.region3 = myProvince.data
      }
    },

    region3(paramID) {
      let pid = this.ruleForm.region3.id || paramID
      let obj = this.ruleForm.region3
      this.SearchItem(pid, obj)

      this.AddressCombination["area"] = this.SearchItem(pid, obj)
      console.log(this.AddressCombination)
    },
    // 获取省份信息
    async getInfor() {
      let Province = await this.$http({
        method: "post",
        url: "/api/home/index/linkagearea",
        data: {}
      })
      const myProvince = Province.data
      if (myProvince.State.Code == 200) {
        // console.log(myProvince.data)
        this.ruleForm.region1 = myProvince.data
      }
    },

    // 发票按钮选择
    selectMethods(index, btn) {
      console.log(index, btn, this.flag)
      let myflag = this.flag  // 后台获取的数值
      switch (myflag) {
        case 1:
          if (index == 0) {
            this.show1 = true
            this.show2 = true
            this.show3 = true
          } else if (index == 1) {
            this.show1 = false
            this.show2 = false
            this.show3 = false
          }
          break
        case 2:
          if (index == 1) {
            this.show1 = false
            this.show2 = false
            this.show3 = false
          } else {
            this.show1 = false
            this.show2 = true
            this.show3 = true
          }
          break
        case 3:
          if (index == 0) {
            this.show1 = true
            this.show2 = true
            this.show3 = true
          } else if (index == 1) {
            this.show1 = false
            this.show2 = false
            this.show3 = false
          }
          break
        case 4:
          console.log('不会出现4的情况 若是出现了 就是见鬼了...')
          break
      }

      this.act = index
      // 发票的按钮的事件
      let flag = "0"
      if (btn == "不开发票") {               // 不开发票
        flag = "0"
      } else if (btn == "增值税普通发票") {  // 增值税普通发票
        flag = "1"
        this.$emit("InvoiceInfoIDChange", this.addressId)
      } else {                              // 增值税专用发票
        flag = "2"
        this.$emit("InvoiceInfoIDChange", this.addressId)
      }

      this.$store.commit("InvoiceInfoBtn", flag)
      console.log(flag)
    }
  },

  created() {
    this.getInvoice()
  },

  mounted() {
    this.getInfor()
    this.getAddress()
  }
}
</script>
<style lang="scss" scoped>
.container {
  width: 1200px;
  h4 {
    line-height: 50px;
  }
  .careful {
    font-size: 12px;
    letter-spacing: 0.5px;
    line-height: 24px;
    span {
      color: #ff0000;
    }
    i {
      color: #0078ff;
      cursor: pointer;
    }
  }
  .InvoiceK {
    background: #f6f6f6;
    border: 1px #d7d7d7 dashed;
    // div[data-v-23819362]{
    //     padding: 0;
    // }
    h6 {
      width: 100%;
      height: 20px;
      margin: auto;
      border-bottom: 1px dashed #d7d7d7;
    }
    h5 {
      font-weight: normal;
      line-height: 40px;
      position: relative;
      i {
        color: #858585;
      }
      .set {
        position: absolute;
        right: 0px;
        top: 6.5px;
      }
    }
    .deshk {
      padding: 10px;
      .active {
        background: #0078ff;
        color: #fff;
      }
      .dialogk2 {
        width: 360px;
        margin: auto;
      }
    }
    .taitou {
      .el-input {
        width: 40%;
      }
    }
    .DiologS {
      width: 1200px;
      margin: auto;
      h4 {
        line-height: 50px;
      }
      .flexk {
        width: 1128px;
        height: 47px;
        line-height: 47px;
        background: #f4f4f4;
        border: 1px solid #e2e2e2;
        padding: 0 36px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        p {
          width: 700px;
        }
      }
      .el-dialog {
        .el-dialog__body {
          .dialogk {
            width: 100%;
            position: relative;
            .content-left {
              width: 100%;
              li {
                display: flex;
                flex-direction: row;
                justify-content: space-between;
                padding: 10px 0px;
                .el-radio {
                  flex: 1;
                  display: inline-block;
                  word-break: break-all; // 超出部分换行
                  white-space: normal; // 超出部分换行
                  .el-radio__label {
                    display: inline-block;
                    width: 80%;
                    overflow: hidden;
                  }
                }
                .el-button {
                  margin-left: 20px;
                }
              }
            }
          }
          .dialogk2 {
            width: 480px;
            margin: auto;
          }
          .el-button[size="mini"] {
            margin-left: 10px;
          }
        }
      }
    }
  }
}
</style>

